﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dblayer;
using Modellayer;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace ControlLayer
{
    public class ReservationCtr
    {
        DbReservation dbReservation;
        ShowCtr showCtr;
        Reservation reservation;
        PersonCtr personCtr;
        DbSeat dbSeat;
        private static ReservationCtr instance;

        private ReservationCtr()
        {
            dbReservation = new DbReservation();
            showCtr = ShowCtr.getInstance();
            dbSeat = new DbSeat();
            personCtr = PersonCtr.getInstance();
        }

        public static ReservationCtr getInstance()
        {
            if (instance == null)
            {
                instance = new ReservationCtr();
            }
            return instance;
        }

        public void createReservation(List<int> seatNumbers, int showId, int phoneNumber)
        {
            int resId = dbReservation.getMax();
            Show show = showCtr.findShow(showId);
            List<Seat> seats = show.seats;
            Person person = personCtr.findPerson(phoneNumber);
            reservation = new Reservation(resId, show, person);
            dbReservation.createReservation(reservation);
            foreach (int seatNbr in seatNumbers)
            {
                int index = 0;
                Boolean found = false;
                while (index < seats.Count && found == false)
                {
                    Seat seat = seats.ElementAt(index);
                    if (seat.seatNumber == seatNbr && seat.status == 2)
                    {
                        showCtr.reserveSeat(showId, seatNbr, resId);
                        found = true;
                    }

                    else
                        index++;
                }
            }
        }

        public void deleteReservation(int reservationId)
        {
            Reservation reservation = dbReservation.findReservation(reservationId);
            reservation.seats = dbSeat.findSeatWithReservationId(reservationId);
            foreach(Seat seat in reservation.seats)
            {
                showCtr.unLockSeat(reservation.show.showId, seat.seatNumber);
            }
            dbReservation.deleteReservation(reservationId);
        }

        public Reservation findReservation(int reservationId)
        {
            Reservation reservation = dbReservation.findReservation(reservationId);
            if (reservation != null)
            {
                reservation.seats = dbSeat.findSeatWithReservationId(reservationId);
            }
            return reservation;
        }

        public int getLastMax()
        {
            return dbReservation.getLastMax();
        }
    }
}